package com.qqt.csr.ixport.task;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Author: yang hao
 * @Date: 2025/2/6 14:55
 * @Description: 动态分片策略
 **/
@Deprecated
public class DynamicChunkStrategy implements ChunkStrategy {

    /**
     * 最大分片大小
     */
    private static final int MAX_CHUNK_SIZE = 1000;

    /**
     * 最大分片字节数
     */
    private static final long MAX_CHUNK_BYTES = 1024 * 1024;

    /**
     * 分片
     * @param reader 缓冲读取器
     * @return 分片
     * @throws IOException IO异常
     */
    @Override
    public Iterator<List<String>> chunk(BufferedReader reader) throws IOException {
        return new Iterator<>() {
            /**
             * 是否有下一条记录
             */
            private final AtomicBoolean hasNext = new AtomicBoolean(true);

            /**
             * 是否有下一条记录
             * @return 是否有下一条记录
             */
            @Override
            public boolean hasNext() {
                return hasNext.get();
            }

            /**
             * 下一条记录
             * @return 下一条记录
             */
            @Override
            public List<String> next() {
                try {
                    List<String> chunk = new ArrayList<>();
                    long byteCount = 0;
                    String line;

                    while ((line = reader.readLine()) != null) {
                        chunk.add(line);
                        byteCount += line.getBytes(StandardCharsets.UTF_8).length;

                        if (chunk.size() >= MAX_CHUNK_SIZE || byteCount >= MAX_CHUNK_BYTES) {
                            return chunk;
                        }
                    }
                    hasNext.set(false);
                    return chunk;
                } catch (IOException e) {
                    hasNext.set(false);
                    throw new RuntimeException("Error reading file", e);
                }
            }
        };
    }
}
